package cn.com.onlinetool.jt809.controller;

import cn.com.onlinetool.jt809.mapper.SysJt809UserConfigMapper;
import cn.com.onlinetool.jt809.pojo.SysJt809UserConfig;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : dlm
 * @date : 2022/2/24 0024 10:00
 */
@RestController
@RequestMapping("/jt809/sys/user/conifg")
public class SysJt809UserController {

    public final static String KEY = "jt809:sys:user:config:";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysJt809UserConfigMapper sysJt809UserConfigMapper;

    @PostConstruct
    public void initCache(){
        loadCache();
    }

    @GetMapping("/refresh")
    public Map<String,Object> refreshCache(){
        loadCache();
        HashMap<String, Object> result = new HashMap<>();
        result.put("code",0);
        result.put("msg","刷新缓存成功");
        return result;
    }

    /**
     * 将jt809用户配置加入缓存
     */
    public void loadCache(){
        List<SysJt809UserConfig> list = sysJt809UserConfigMapper.getAllList();
        if (list != null && list.size() >0){
            HashOperations hashOperations = redisTemplate.opsForHash();
            list.forEach(item ->{
                hashOperations.put(KEY,item.getUserId().toString(), JSON.toJSONString(item));
            });
        }
    }
}
